package cn.edu.pku.ss.lbs.blip;

import cn.edu.pku.ss.lbs.position.SignalSource;
import com.blipsystems.blipnet.api.blipserver.BlipServer;
import com.blipsystems.blipnet.api.blipserver.BlipServerConnection;
import com.blipsystems.blipnet.api.blipserver.BlipServerException;
import com.blipsystems.blipnet.api.util.BlipNetSecurityManager;

import java.util.HashMap;
import java.util.Map;

public class BlipUtility {
    private static BlipUtility ourInstance;

    public static BlipUtility getInstance() {
        if (ourInstance == null) ourInstance = new BlipUtility();
        return ourInstance;
    }

    private BlipConfig config = new BlipConfig();
    private Map<String, BlipDevice> deviceMap = new HashMap<String, BlipDevice>();
    private BlipSignalSource source = new BlipSignalSource();

    private BlipUtility() {
        try {
            System.setSecurityManager(new BlipNetSecurityManager());
            for (BlipServerConfig serverConfig : config.getServerConfigList()) {
                String username = serverConfig.getUsername();
                String password = serverConfig.getPassword();
                String serverHost = serverConfig.getServerHost();
                BlipServerConnection connection = BlipServer.getConnection(username, password, serverHost);
                for (BlipDeviceConfig deviceConfig : serverConfig.getDeviceConfigList()) {
                    BlipDevice device = new BlipDevice(connection, deviceConfig, source);
                    deviceMap.put(deviceConfig.getZone(), device);
                }
            }
        } catch (BlipServerException e) {
            e.printStackTrace();
        }
    }

    public SignalSource getSignalSource() {
        return source;
    }

    public void sendMessage(String station, String terminal, String message) {
        deviceMap.get(station).sendMessage(terminal, message);
    }

    public void sendFile(String station, String terminal, String path) {
        deviceMap.get(station).sendFile(terminal, path);
    }
}